extends Camera2D

@export var followTarget:Node2D
@export var followSpeed = 7

@export_category("Limit")
@export var left = -20
@export var right = 340
@export var top = -20
@export var bottom = 200

func _ready():
	add_to_group(Consts.GROUP_SCENE_CAMERA)
	setRender2ScreenCapture()
	
	if not followTarget: tryGetCamFollowTarget()
	
	
func setRender2ScreenCapture():
	pass


func _exit_tree():
	remove_from_group(Consts.GROUP_SCENE_CAMERA)
	
	
func tryGetCamFollowTarget():
	var currentScene = get_tree().current_scene
	followTarget = Global.getChildNodeByName(currentScene, Consts.PLAYER_NODE_NAME)
	if not followTarget:
		return
		
	Global.setCamPosition(self, getCamFollowTargetPosition())
	

func _physics_process(delta):
	if not followTarget:
		tryGetCamFollowTarget()
		if not followTarget: return
	
	var targetCamPos = getCamFollowTargetPosition()
	Global.setCamPosition(self, Global.getCamPosition(self).lerp(targetCamPos, followSpeed * delta))
	

func getCamFollowTargetPosition():
	var result = followTarget.position - Global.viewportSize / 2.0
	if result.x < left: result.x = left
	if result.y < top: result.y = top
	if (result.x + Global.viewportWidth) > right: result.x = right - Global.viewportWidth
	if result.y + Global.viewportHeight > bottom: result.y = bottom - Global.viewportHeight
	return result
	
	
	
	
